const express = require('express');
const path = require('path');
const chalk = require('chalk');
const bodyParser = require('body-parser');
const projectconf = require(path.join(__dirname, 'conf/project.conf'));
const { proxyArr } = require(path.join(__dirname, 'conf/app.conf'));
const { createProxyMiddleware } = require('http-proxy-middleware');

let app = express();
app.listen(projectconf.port);

/**处理body参数 */
app.use(bodyParser.urlencoded({ extended: false }))

/**代理后端服务 */
app.use('/menu', require(path.join(__dirname, 'routers/menu')));
app.use('/plug', require(path.join(__dirname, 'routers/plug')));
app.use('/func', require(path.join(__dirname, 'routers/func')));
app.use('/uploadplug', require(path.join(__dirname, 'routers/uploadplug')));
app.use('/platform', require(path.join(__dirname, 'routers/platform')));

/**一期代理，已废弃，采用重定向 */
// app.use('/login',createProxyMiddleware(
//     {
//         target: 'http://192.168.6.109:8080/officeroom/',
//         changeOrigin: true,
//         pathRewrite: {
//             '/login': '/index'
//         }
//     }
// ));

/**代理插件的后台接口 */
proxyArr.forEach(myproxy => {
    app.use(
        myproxy.key,
        createProxyMiddleware(
            {
                target: myproxy.target,
                changeOrigin: true,
                pathRewrite: myproxy.pathRewrite
            })
    );
})


/**代理前端静态文件 */
app.use('/webapp', express.static(path.join(__dirname, './webapp')));

console.log(chalk.yellow("后端服务地址: ") + chalk.green("http://" + projectconf.ip + ":" + projectconf.port));
console.log(chalk.yellow("页面登录地址: ") + chalk.green("http://" + projectconf.ip + ":" + projectconf.port + "/webapp/public"));

//404判断
app.use(function (req, res) {
    // res.sendFile(__dirname + "/" + "404.html");
    res.send({ state: '404', msg: '您请求的链接不存在' });
});